package com.starsea.book.ui.newpage

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SpanUtils
import com.blankj.utilcode.util.ToastUtils
import com.starsea.book.BuildConfig
import com.starsea.book.R
import com.starsea.book.base.VMBaseActivity
import com.starsea.book.constant.AppConst
import com.starsea.book.constant.PreferKey
import com.starsea.book.databinding.ActivityLoginBinding
import com.starsea.book.help.IntentData
import com.starsea.book.model.ReadBook
import com.starsea.book.ui.browser.WebViewActivity
import com.starsea.book.ui.main.MainActivity
import com.starsea.book.ui.newpage.utils.AppManager
import com.starsea.book.ui.newpage.utils.CountTimeState
import com.starsea.book.ui.newpage.utils.visibleOrGone
import com.starsea.book.ui.newpage.viewmodel.LoginViewModel
import com.starsea.book.utils.EncryptUtil
import com.starsea.book.utils.gone
import com.starsea.book.utils.isPhone
import com.starsea.book.utils.putPrefBoolean
import com.starsea.book.utils.putPrefString
import com.starsea.book.utils.startActivity
import com.starsea.book.utils.toastOnUi
import com.starsea.book.utils.viewbindingdelegate.viewBinding
import com.starsea.book.utils.visible
import splitties.init.appCtx
import splitties.views.InputType.Companion.phone

/**
 * @author Lee
 * @createTime 2024-01-10 15 GMT+8
 * @desc :
 */
class LoginActivity : VMBaseActivity<ActivityLoginBinding, LoginViewModel>() {

    override val viewModel: LoginViewModel by viewModels<LoginViewModel>()

    override val binding: ActivityLoginBinding by viewBinding(ActivityLoginBinding::inflate)

    companion object {
        @JvmStatic
        fun start(context: Context) {
            val starter = Intent()
                .setClassName(BuildConfig.APPLICATION_ID, LoginActivity::class.java.name)
            context.startActivity(starter)
        }
    }

    override
    fun onActivityCreated(savedInstanceState: Bundle?) {

        AppManager.getInstance().addActivity(this)


        binding.retPhone.addTextChangedListener {
            val phone = it.toString()
            binding.rtvLogin.isEnabled = !TextUtils.isEmpty(phone) && phone.length == 11
                    && !TextUtils.isEmpty(binding.retCode.text.toString())

            binding.rtvGetCode.isEnabled = !TextUtils.isEmpty(phone) && phone.length == 11

        }
        binding.retCode.addTextChangedListener {
            val phone = binding.retPhone.text.toString()

            binding.rtvLogin.isEnabled = !TextUtils.isEmpty(phone) && phone.length == 11
                    && !TextUtils.isEmpty(binding.retCode.text.toString())
        }

        binding.rtvGetCode.setOnClickListener {
            val phone = binding.retPhone.text.toString()
            if (!phone.isPhone()) {
                ToastUtils.showShort("请输入正确的手机号码")
                return@setOnClickListener
            }

            // 获取验证码
            viewModel.getCode(phone)
        }

        binding.rtvLogin.setOnClickListener {

            val phone = binding.retPhone.text.toString()

            if (!binding.rcbAgreeDeal.isChecked) {
                ToastUtils.showShort("请先阅读并同意《用户协议》和《隐私政策》")
                return@setOnClickListener
            }
            if (!phone.isPhone()) {
                ToastUtils.showShort("请输入正确的手机号码")
                return@setOnClickListener
            }

            val code = binding.retCode.text.toString()
            if (TextUtils.isEmpty(code)) {
                ToastUtils.showShort("请输入验证码")
                return@setOnClickListener
            }
            // 获取验证码
            viewModel.login(phone, code, this)
        }

        viewModel.codeResult.observe(this) {
            when (it) {
                200 -> {
                    ToastUtils.showShort("短信发送成功")
                    viewModel.count()
                }

                else -> {

                }
            }
        }



        setDealText(0)


        viewModel.loginResutl.observe(this) {
            when (it.status) {
                200 -> {
//                    "登录成功".toastShort()
//                    CacheUtil.setToken(it.data)
                    appCtx.putPrefString(PreferKey.token, it.data)
                    appCtx.putPrefBoolean(PreferKey.isLogin, true)
//          startActivity<com.starsea.book.ui.page.activity.MainActivity>()
//          com.starsea.book.ui.page.activity.MainActivity.start(mContext)
                    startActivity<MainActivity>()
                    finish()
                }

                else -> {
//          ToastUtils.showShort(it.error.errorMsg)
                }

            }
        }


        viewModel.errorResult.observe(this) {
            ToastUtils.showShort(it ?: "")
        }

        viewModel.countTime.observe(this) {
            when (it) {
                is CountTimeState.Finish -> {
                    binding.rtvGetCode.isEnabled = true
                    binding.rtvGetCode.text = "重新发送"
                }

                is CountTimeState.Loading -> {
                    binding.rtvGetCode.isEnabled = false
                    binding.rtvGetCode.text = "${it.data}s后重新发送"
                }
            }
        }


    }

    fun setDealText(type: Int) {
        binding.rcbDeal.movementMethod = LinkMovementMethod.getInstance()
        binding.rcbDeal.text = SpanUtils().append(
            if (type == 0) "我已阅读并同意" else "首次登录会自动创建新账号，且代表同意"
        )
            .append("《用户协议》")
            .setClickSpan(
                ContextCompat.getColor(this, R.color.color_20002C),
                false
            ) {
                startActivity<WebViewActivity> {
                    putExtra("title", "用户协议")
                    putExtra("url", "http://admin.blblcm.com/yhxy.html")
                }
            }
            .append("和")
            .append("《隐私政策》")
            .setClickSpan(
                ContextCompat.getColor(this, R.color.color_20002C),
                false
            ) {
                startActivity<WebViewActivity> {
                    putExtra("title", "隐私政策")
                    putExtra("url", "http://admin.blblcm.com/ysxy.html")
                }
            }
            .create()
    }


}




